package qq.tool;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import qq.mapper.SignInMapper;
import qq.mapper.UserMapper;

import java.io.IOException;
import java.io.Reader;

public class MybatisTool {
    private static SqlSessionFactory SQL_SESSION_FACTORY;

    /**
     * 构造SqlSession
     * @return SqlSession
     * @throws IOException
     */
    public static SqlSession getSqlSession() throws IOException {
        if(SQL_SESSION_FACTORY==null){
            synchronized (MybatisTool.class){
                SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
                try(Reader reader = Resources.getResourceAsReader("mybatis-config.xml")){
//                    //3,创建SqlSessionFactory,SqlSessionFactory在系统中必须是单例的
                    SQL_SESSION_FACTORY = sqlSessionFactoryBuilder.build(reader);
                   SQL_SESSION_FACTORY.getConfiguration().addMapper(UserMapper.class);
                    SQL_SESSION_FACTORY.getConfiguration().addMapper(SignInMapper.class);
               }
            }
        }
        return SQL_SESSION_FACTORY.openSession();
    }
}
